package com.places.googleplacesandmaps;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

@TargetApi(9)
public class OwnerDetails extends Activity implements View.OnClickListener {
		
	Intent i;
	static final int TIME_DIALOG_ID = 0;
	private int pHour;
    private int pMinute;
	TextView txtName, txtLocation,txtTime;
	TextView txtMon,txtMonOpen,txtMonOpenTime,txtMonClose,txtMonCloseTime;
	Button btnMonOpen,btnMonClose;
	TextView txtTue,txtTueOpen,txtTueOpenTime,txtTueClose,txtTueCloseTime;
	Button btnTueOpen,btnTueClose;
	TextView txtWed,txtWedOpen,txtWedOpenTime,txtWedClose,txtWedCloseTime;
	Button btnWedOpen,btnWedClose;
	TextView txtThu,txtThuOpen,txtThuOpenTime,txtThuClose,txtThuCloseTime;
	Button btnThuOpen,btnThuClose;
	TextView txtFri,txtFriOpen,txtFriOpenTime,txtFriClose,txtFriCloseTime;
	Button btnFriOpen,btnFriClose;
	TextView txtSat,txtSatOpen,txtSatOpenTime,txtSatClose,txtSatCloseTime;
	Button btnSatOpen,btnSatClose;
	TextView txtSun,txtSunOpen,txtSunOpenTime,txtSunClose,txtSunCloseTime;
	Button btnSunOpen,btnSunClose;
	Button btnSave;
	JSONArray jArray;
	JSONObject json_data;
	String loc_name="",loc_addr="",uname="";
	TextView tv;
	boolean present =false;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ownerdetails);
        Bundle gotBasket = getIntent().getExtras();
        uname = gotBasket.getString("username");
        loc_name = gotBasket.getString("shopname");
        loc_addr = gotBasket.getString("location");

        setupVariables(); 
	}
	
	private void setupVariables() {
		
        txtName = (TextView)findViewById(R.id.textViewnm);
        txtLocation = (TextView)findViewById(R.id.textViewloc);
        txtTime = (TextView)findViewById(R.id.textViewhoop);
        txtName.setText(loc_name);
        txtLocation.setText(loc_addr);
        //Monday
        txtMon = (TextView)findViewById(R.id.textViewmon);
        txtMonOpen = (TextView)findViewById(R.id.textViewopmon);
        txtMonOpenTime = (TextView)findViewById(R.id.textViewopmontime);
        btnMonOpen = (Button)findViewById(R.id.buttonopmon);
        btnMonOpen.setOnClickListener(this);
        txtMonClose = (TextView)findViewById(R.id.textViewclmon);
        txtMonCloseTime = (TextView)findViewById(R.id.textViewclmontime);
        btnMonClose = (Button)findViewById(R.id.buttonclmon);
        btnMonClose.setOnClickListener(this);
        
      //Tuesday
        txtTue = (TextView)findViewById(R.id.textViewtue);
        txtTueOpen = (TextView)findViewById(R.id.textViewoptue);
        txtTueOpenTime = (TextView)findViewById(R.id.textViewoptuetime);
        btnTueOpen = (Button)findViewById(R.id.buttonoptue);
        btnTueOpen.setOnClickListener(this);
        txtTueClose = (TextView)findViewById(R.id.textViewcltue);
        txtTueCloseTime = (TextView)findViewById(R.id.textViewcltuetime);
        btnTueClose = (Button)findViewById(R.id.buttoncltue);
        btnTueClose.setOnClickListener(this);
        
      //Wednesday
        txtWed = (TextView)findViewById(R.id.textViewwed);
        txtWedOpen = (TextView)findViewById(R.id.textViewopwed);
        txtWedOpenTime = (TextView)findViewById(R.id.textViewopwedtime);
        btnWedOpen = (Button)findViewById(R.id.buttonopwed);
        btnWedOpen.setOnClickListener(this);
        txtWedClose = (TextView)findViewById(R.id.textViewclwed);
        txtWedCloseTime = (TextView)findViewById(R.id.textViewclwedtime);
        btnWedClose = (Button)findViewById(R.id.buttonclwed);
        btnWedClose.setOnClickListener(this);
        
      //Thursday
        txtThu = (TextView)findViewById(R.id.textViewthu);
        txtThuOpen = (TextView)findViewById(R.id.textViewopthu);
        txtThuOpenTime = (TextView)findViewById(R.id.textViewopthutime);
        btnThuOpen = (Button)findViewById(R.id.buttonopthu);
        btnThuOpen.setOnClickListener(this);
        txtThuClose = (TextView)findViewById(R.id.textViewclthu);
        txtThuCloseTime = (TextView)findViewById(R.id.textViewclthutime);
        btnThuClose = (Button)findViewById(R.id.buttonclthu);
        btnThuClose.setOnClickListener(this);
        
      //Friday
        txtFri = (TextView)findViewById(R.id.textViewfri);
        txtFriOpen = (TextView)findViewById(R.id.textViewopfri);
        txtFriOpenTime = (TextView)findViewById(R.id.textViewopfritime);
        btnFriOpen = (Button)findViewById(R.id.buttonopfri);
        btnFriOpen.setOnClickListener(this);
        txtFriClose = (TextView)findViewById(R.id.textViewclfri);
        txtFriCloseTime = (TextView)findViewById(R.id.textViewclfritime);
        btnFriClose = (Button)findViewById(R.id.buttonclfri);
        btnFriClose.setOnClickListener(this);
        
      //Saturday
        txtSat = (TextView)findViewById(R.id.textViewsat);
        txtSatOpen = (TextView)findViewById(R.id.textViewopsat);
        txtSatOpenTime = (TextView)findViewById(R.id.textViewopsattime);
        btnSatOpen = (Button)findViewById(R.id.buttonopsat);
        btnSatOpen.setOnClickListener(this);
        txtSatClose = (TextView)findViewById(R.id.textViewclsat);
        txtSatCloseTime = (TextView)findViewById(R.id.textViewclsattime);
        btnSatClose = (Button)findViewById(R.id.buttonclsat);
        btnSatClose.setOnClickListener(this);
        
      //Sunday
        txtSun = (TextView)findViewById(R.id.textViewsun);
        txtSunOpen = (TextView)findViewById(R.id.textViewopsun);
        txtSunOpenTime = (TextView)findViewById(R.id.textViewopsuntime);
        btnSunOpen = (Button)findViewById(R.id.buttonopsun);
        btnSunOpen.setOnClickListener(this);
        txtSunClose = (TextView)findViewById(R.id.textViewclsun);
        txtSunCloseTime = (TextView)findViewById(R.id.textViewclsuntime);
        btnSunClose = (Button)findViewById(R.id.buttonclsun);
        btnSunClose.setOnClickListener(this);
        
        btnSave = (Button)findViewById(R.id.buttonsave);
        btnSave.setOnClickListener(this);
        
        InputStream is=null;
    	String line = null;
    	String result="";
    	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectNetwork() // or .detectAll() for all detectable problems
        .penaltyDialog()  //show a dialog
        .permitNetwork() //permit Network access 
        .build());
    	try{
        	
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new      
            HttpPost("http://project2.site11.com/getTime.php");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.i("postData", response.getStatusLine().toString());
        }catch(Exception e)
        {
            Log.e("log_tag", "Error in http connection "+e.toString());
        }
        
        
        //parsing http response into string
        System.out.println("6");
        long h=1;
        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            System.out.println("before converting");
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection" +e.toString());
        }
        
        
        //parsing json
        try{	 
        	if(result!=null)
        	{	
        		jArray = new JSONArray(result);
        		for(int i=0;i<jArray.length();i++)
				{
					json_data = jArray.getJSONObject(i);
					String loc = json_data.getString("Location");
					if(loc.equals(loc_addr))
					{
						present = true;
						String type = json_data.getString("Type");
						if(type.equals("open"))
						{
							txtMonOpenTime.setText(json_data.getString("Monday"));
							txtTueOpenTime.setText(json_data.getString("Tuesday"));
							txtWedOpenTime.setText(json_data.getString("Wednesday"));
							txtThuOpenTime.setText(json_data.getString("Thursday"));
							txtFriOpenTime.setText(json_data.getString("Friday"));
							txtSatOpenTime.setText(json_data.getString("Saturday"));
							txtSunOpenTime.setText(json_data.getString("Sunday"));
						}
							
						else
						{
							txtMonCloseTime.setText(json_data.getString("Monday"));
							txtTueCloseTime.setText(json_data.getString("Tuesday"));
							txtWedCloseTime.setText(json_data.getString("Wednesday"));
							txtThuCloseTime.setText(json_data.getString("Thursday"));
							txtFriCloseTime.setText(json_data.getString("Friday"));
							txtSatCloseTime.setText(json_data.getString("Saturday"));
							txtSunCloseTime.setText(json_data.getString("Sunday"));
						}
					}
				}
            }
            }
        catch(JSONException e){
            Log.e("log_tag", "Error parsing data" +e.toString());
        }
        
        if( present == false){
        	final Calendar cal = Calendar.getInstance();
            pHour = cal.get(Calendar.HOUR_OF_DAY);
            pMinute = cal.get(Calendar.MINUTE);
     
            /** Display the current time in the TextView */
            
            tv = (TextView)findViewById(R.id.textViewopmontime);
            updateDisplay();
            tv = (TextView)findViewById(R.id.textViewclmontime);
            updateDisplay();
            tv = (TextView)findViewById(R.id.textViewoptuetime);
            updateDisplay();
            tv = (TextView)findViewById(R.id.textViewcltuetime);
            updateDisplay();
            tv = (TextView)findViewById(R.id.textViewopwedtime);
            updateDisplay();
            tv = (TextView)findViewById(R.id.textViewclwedtime);
            updateDisplay();
            tv = (TextView)findViewById(R.id.textViewopthutime);
            updateDisplay();
            tv = (TextView)findViewById(R.id.textViewclthutime);
            updateDisplay();
            tv = (TextView)findViewById(R.id.textViewopfritime);
            updateDisplay();
            tv = (TextView)findViewById(R.id.textViewclfritime);
            updateDisplay();
            tv = (TextView)findViewById(R.id.textViewopsattime);
            updateDisplay();
            tv = (TextView)findViewById(R.id.textViewclsattime);
            updateDisplay();
            tv = (TextView)findViewById(R.id.textViewopsuntime);
            updateDisplay();
            tv = (TextView)findViewById(R.id.textViewclsuntime);
            updateDisplay();
            
        }
 
		
	}
	
    public void onClick(View v){
        switch (v.getId()) {
        	case R.id.buttonopmon:
        		tv = (TextView)findViewById(R.id.textViewopmontime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttonclmon:
        		tv = (TextView)findViewById(R.id.textViewclmontime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttonoptue:
        		tv = (TextView)findViewById(R.id.textViewoptuetime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttoncltue:
        		tv = (TextView)findViewById(R.id.textViewcltuetime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttonopwed:
        		tv = (TextView)findViewById(R.id.textViewopwedtime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttonclwed:
        		tv = (TextView)findViewById(R.id.textViewclwedtime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttonopthu:
        		tv = (TextView)findViewById(R.id.textViewopthutime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttonclthu:
        		tv = (TextView)findViewById(R.id.textViewclthutime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttonopfri:
        		tv = (TextView)findViewById(R.id.textViewopfritime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttonclfri:
        		tv = (TextView)findViewById(R.id.textViewclfritime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttonopsat:
        		tv = (TextView)findViewById(R.id.textViewopsattime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttonclsat:
        		tv = (TextView)findViewById(R.id.textViewclsattime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttonopsun:
        		tv = (TextView)findViewById(R.id.textViewopsuntime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttonclsun:
        		tv = (TextView)findViewById(R.id.textViewclsuntime);
            	showDialog(TIME_DIALOG_ID);
            	break;
        	case R.id.buttonsave:
        		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(15);
            	
            	nameValuePairs.add(new BasicNameValuePair("txtMonOpenTime",txtMonOpenTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("txtMonCloseTime",txtMonCloseTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("txtTueOpenTime",txtTueOpenTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("txtTueCloseTime",txtTueCloseTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("txtWedOpenTime",txtWedOpenTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("txtWedCloseTime",txtWedCloseTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("txtThuOpenTime",txtThuOpenTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("txtThuCloseTime",txtThuCloseTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("txtFriOpenTime",txtFriOpenTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("txtFriCloseTime",txtFriCloseTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("txtSatOpenTime",txtSatOpenTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("txtSatCloseTime",txtSatCloseTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("txtSunOpenTime",txtSunOpenTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("txtSunCloseTime",txtSunCloseTime.getText().toString()));
            	nameValuePairs.add(new BasicNameValuePair("uname",uname));
            	
            	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectNetwork() // or .detectAll() for all detectable problems
                .penaltyDialog()  //show a dialog
                .permitNetwork() //permit Network access 
                .build()); 
              //http post
                try{
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://project2.site11.com/addTime.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    //HttpEntity entity = response.getEntity();
                    //InputStream is = entity.getContent();
                    Log.i("postData", response.getStatusLine().toString());
                   
                }

                catch(Exception e)
                {
                    Log.e("log_tag", "Error in http connection "+e.toString());
                    
                }
                Context context = getApplicationContext();
				CharSequence text = "Details saved Successfully!";
				int duration = Toast.LENGTH_LONG;
				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
				i = new Intent(OwnerDetails.this, FrontPage.class);
    			OwnerDetails.this.startActivity(i);
            	
    		
        }
    }
    private void updateDisplay() {
    		tv.setText(new StringBuilder().append(pad(pHour)).append(":").append(pad(pMinute)));
    }
    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
            new TimePickerDialog.OnTimeSetListener() {
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    pHour = hourOfDay;
                    pMinute = minute;
                    updateDisplay();
                   
                }
            };
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this,
                    mTimeSetListener, pHour, pMinute, false);
        }
        return null;
    }
}
